package ma.mindware.mpm.technicalservice.db;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import jpmapper.core.FOREIGN;
import jpmapper.core.Transaction;
import jpmapper.exceptions.JPMapperException;
import ma.mindware.met.core.technicalservice.DBService;
import ma.mindware.met.core.technicalservice.TechnicalServiceException;

public class PagerDBService extends DBService{

	
	public PagerDBService(Object[] params) throws TechnicalServiceException{
		super(params);
	}
	
	public ArrayList<Object> list(Class className,Long start,Long step) throws TechnicalServiceException{
		Transaction transaction = null;
		ArrayList<Object> listPagerObject=null;
		try {
			transaction=this.jpmapperFacade.getNewTransaction();
			transaction.begin();
			listPagerObject=transaction.getAll(className.newInstance(),"1",start,step,"1");
			Integer j=0;
			while(j<listPagerObject.size()){
				Field field[]=className.getDeclaredFields();
				Integer i=0;
				while(i<field.length){
					if(field[i].isAnnotationPresent(FOREIGN.class)){
						Object object=field[i].getType().newInstance();
						object=transaction.get(listPagerObject.get(j), object);
						Class[] typeObject=new Class[1];
						typeObject[0]=field[i].getType();
						@SuppressWarnings("unchecked")
						Method method=className.getMethod("set"+field[i].getType().getSimpleName(),typeObject );
						Object[] valueObject=new Object[1];
						valueObject[0]=object;
						method.invoke(listPagerObject.get(j), valueObject);
					}
					i++;
				}
				j++;
			}
			transaction.end();
		}catch (JPMapperException e) {
			transaction.end();
			throw new TechnicalServiceException(0, e.getMessage(),e);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listPagerObject;
	}
	
	
}
